package com.lxf.clouduser.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lxf.clouduser.service.CaptchaService;
import liquibase.pro.packaged.S;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author 罗兴发
 * @data 2025/9/25 11:25
 * @description：图片验证码-控制层
 */
@RestController
@CrossOrigin  //跨域
@RequestMapping("/v1")
public class CaptchaController {
    @Resource
    CaptchaService captchaService;

    /**
     * 获取随机生成的图片数字验证码
     * @return
     */
    @GetMapping("/getImageBase64")
    public String getImageBase64(){
        JSONObject js =new JSONObject();
        String imageBase64 = captchaService.generateCaptcha();

        //封装json
        js.put("code",200);
        js.put("msg","Success");
        js.put("data",imageBase64);

        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }

    /**
     * 用户输入验证码，验证是否正确
     * @param json
     * @return
     */
    @PostMapping("/userCaptcha")
    public String userCaptcha(@RequestBody JSONObject json){
        JSONObject js = new JSONObject();
        String answer = json.getString("answer");
        boolean b = captchaService.validateCaptcha(answer);
        if (b){
            js.put("code",200);
            js.put("msg","Success");
        }else{
            js.put("code",401);
            js.put("msg","The Captcha Is Error !");
        }

        return JSONObject.toJSONString(js,SerializerFeature.WriteMapNullValue);
    }
}
